package com.warmheart.base.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.warmheart.base.executor.MdcThreadPoolTaskExecutor;
import com.warmheart.base.session.SessionLocalUtils;
import com.warmheart.core.util.cache.DictCacheService;

public class BaseController {

    private static Logger logger = LoggerFactory.getLogger(BaseController.class);

    @Autowired(required = false)
    protected DictCacheService dictCacheService;

    @Autowired
    protected MdcThreadPoolTaskExecutor mdcThreadPoolTaskExecutor;

    /**
     * 
     * @Title: getJsonParams
     * @Description: 将Post流传入的JSON参数转化为对象
     * @author ZhangJianyang
     * @param request
     * @param classType
     * @return
     * @throws Exception
     */
    protected <T> T getJsonParams(HttpServletRequest request, Class<T> classType) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            map = getJsonMap(request);
        } catch (Exception e) {
            // 记录异常堆栈信息
            logger.error("获取请求数据异常：" + e.getMessage(), e);
        }
        ObjectMapper mapper = new ObjectMapper();
        String jsonStr = mapper.writeValueAsString(map);
        return mapper.readValue(jsonStr, new TypeReference<T>() {
        });
    }

    /**
     * 
     * @Title: getJsonMap
     * @Description: 将Post流传入的JSON参数转化为Map
     * @author ZhangJianyang
     * @param request
     * @return
     * @throws Exception
     */
    protected Map<String, Object> getJsonMap(HttpServletRequest request) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            StringBuilder sb = getStringBuilder(request);
            if (null != sb && StringUtils.isNotBlank(sb.toString())) {
                ObjectMapper mapper = new ObjectMapper();
                map = mapper.readValue(sb.toString(), new TypeReference<Map<String, Object>>() {
                });
            }
        } catch (Exception e) {
            // 记录异常堆栈信息
            logger.error("解析请求数据异常：" + e.getMessage(), e);
            throw e;
        }
        return map;
    }

    /**
     * 
     * @Title: getStringBuilder
     * @Description: 读取请求内容
     * @author ZhangJianyang
     * @param request
     * @return
     * @throws IOException
     */
    private StringBuilder getStringBuilder(HttpServletRequest request) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), "utf-8"));
        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        return sb;
    }

    /**
     * 
     * @Title: getCurrentUserId
     * @Description: 获取当前登录用户ID
     * @author ZhangJianyang
     * @return
     */
    protected Integer getCurrentUserId() {
        return SessionLocalUtils.getOperator().getLoginUser().getUserId();
    }

    /**
     * 
     * @Title: getCurrentLoginName
     * @Description: 获取当前登录用户登录名
     * @author ZhangJianyang
     * @return
     */
    protected String getCurrentLoginName() {
        return SessionLocalUtils.getOperator().getLoginUser().getLoginName();
    }
}
